package cn.tworice.blog.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * FastDFS集群工具类
 * @author 二饭
 * @email 1786705138@qq.com
 */
@Slf4j
@Component
public class FdfsUtil {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传文件
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public String uploadFile(MultipartFile file) {
        StorePath storePath = null;
        try {
            storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }
        return storePath.getFullPath();
    }

    /**
     * 删除文件
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public void delFile(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(filePath);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.error(e.getMessage());
        }

    }

}
